package com.mocha.bss.domain.rbac.config;

import com.mocha.bss.feign.bo.menu.FunctionBO;
import com.mocha.bss.feign.bo.menu.MainMenuBO;
import com.mocha.bss.feign.bo.menu.SubMenuBO;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: songkui
 * @since: 2022/4/14 16:06
 */
public class MenuXmlUtil {

    public static void doFlushData(String xml) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document doc = reader.read(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
        Element root = doc.getRootElement(); //scshyzh-auth
        List<Element> mainMenuList = root.elements();  //MainMenu
        List<MainMenuBO> dataList = new ArrayList<>(mainMenuList.size());
        List<String> common = null;
        for (Element mainMenu : mainMenuList){
            MainMenuBO mainMenuBO = new MainMenuBO(mainMenu.attributeValue("code"),
                                                    mainMenu.attributeValue("title"));
            mainMenuBO.setSubMenuBOList(doSubMenu(mainMenu));
            if ("999".equals(mainMenu.attributeValue("code"))){
                common = mainMenuBO.getSubMenuBOList().stream().map(SubMenuBO::getPattern).collect(Collectors.toList());
            }else {
                dataList.add(mainMenuBO);
            }
        }

        MochaFunctionManager.flushData(dataList, common);
    }

    private static List<SubMenuBO> doSubMenu(Element mainMenuElement){
        List<Element> subMenuList = mainMenuElement.elements();
        List<SubMenuBO> dataList = new ArrayList<>(subMenuList.size());
        for (Element subMenu : subMenuList){
            SubMenuBO subMenuBO = new SubMenuBO(subMenu.attributeValue("code"),
                                                subMenu.attributeValue("title"),
                                                subMenu.attributeValue("pattern"));
            subMenuBO.setFuncList(doFunction(subMenu, subMenuBO.getPattern()));

            dataList.add(subMenuBO);
        }

        return dataList;
    }

    private static List<FunctionBO> doFunction(Element subMenu, String pattern){
        List<Element> functionList = subMenu.elements();
        List<FunctionBO> dataList = new ArrayList<>(functionList.size());
        for (Element function : functionList){

            dataList.add(new FunctionBO(function.attributeValue("code"),
                                        function.attributeValue("title"),
                                        function.attributeValue("path"), pattern));
        }

        return dataList;
    }

}
